﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace Heyu.Utility
{

    public class EchartUtility
    {

        /// <summary>
        /// 获取饼状图的json数据源
        /// </summary>
        /// <param name="ds"></param>
        /// <returns></returns>
        public static string GetJsonDataOfPie(EchartAttribute ea, DataTable dt)
        {
            string json = "";
            //标题
            string title = "title: { " + ShowAttribute("text", ea.title_text) + ShowAttribute("subtext", ea.title_subtext) + ShowAttribute("x", ea.title_x) + "},";
            //提示框
            string tooltip = "tooltip: { " + ShowAttribute("show", ea.tooltip_show) + ShowAttribute("trigger", ea.tooltip_trigger) + " formatter: \"{a}<br />{b} : {c} ({d}%)\" },";
            //图例
            string legend = "legend: { " + ShowAttribute("orient", ea.legend_orient) + ShowAttribute("x", ea.legend_x) + " data: [" + GetNames(dt) + "] },";
            //工具箱
            string toolbox = "toolbox: { " + ShowAttribute("show", ea.toolbox_show) + " feature: { mark: { show: true }, dataView: { show: true, readOnly: false }, magicType: { show: true, type: ['pie', 'funnel'], option: { funnel: { x: '25%', width: '50%', funnelAlign: 'left', max: 1548 } } }, restore: { show: true }, saveAsImage: { show: true } } },";
            string calculable = ShowAttribute("calculable", ea.calculable);
            //图
            string series = "series : [" + GetSery(dt, "pie") + "]";

            json = title + tooltip + legend + toolbox + calculable + series;
            return "{" + json + " }";
        }
        /// <summary>
        /// 获取柱状图或者线性图的json数据源
        /// </summary>
        /// <param name="ds"></param>
        /// <param name="tableNames"></param>
        /// <returns></returns>
        public static string GetJsonDataOfBarOrLine(EchartAttribute ea, DataSet ds, string[] tableNames)
        {
            string json = "";

            //将DataSet中的所有表，按照指定名称重命名。
            for (int i = 0; i < ds.Tables.Count; i++)
            {
                ds.Tables[i].TableName = tableNames[i];
            }

            //标题
            string title = "title: { " + ShowAttribute("text", ea.title_text) + ShowAttribute("subtext", ea.title_subtext) + ShowAttribute("x", ea.title_x) + "},";
            //提示框
            string tooltip = "tooltip: { " + ShowAttribute("show", ea.tooltip_show) + ShowAttribute("trigger", ea.tooltip_trigger) + "},";
            string legend = "legend: {" + ShowAttribute("x", ea.legend_x) + "data:[" + GetTableNames(ds) + "]},";
            string toolbox = "toolbox: {" + ShowAttribute("show", ea.toolbox_show) + "feature : { mark : {show: true},dataView : {show: true, readOnly: false},magicType : {show: true, type: ['line', 'bar']},restore : {show: true},saveAsImage : {show: true}}},";
            string calculable = ShowAttribute("calculable", ea.calculable);
            string xAxis = "xAxis : [{type : 'category',data : [" + GetNames(ds.Tables[0]) + "] }],";
            string yAxis = "yAxis : [{type : 'value'}],";
            string series = "series : [" + GetSeries(ds) + "]";

            json = title + tooltip + legend + toolbox + calculable + xAxis + yAxis + series;

            return "{" + json + " }";
        }


        #region 获取数据方法


        /// <summary>
        /// 显示属性
        /// </summary>
        /// <param name="att"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string ShowAttribute(string att, string value)
        {
            string res = "";
            if (!string.IsNullOrEmpty(value))
            {
                res = att + ":'" + value + "',";
            }
            return res;
        }
        public static string ShowAttribute(string att, bool value)
        {
            string res = "";
            if (value)
            {
                res = att + ":true,";
            }
            else
            {
                res = att + ":false,";
            }
            return res;
        }
        public static string ShowAttribute(string att, int value)
        {
            string res = "";
            res = att + ":" + value + ",";
            return res;
        }
        public static string ShowAttributes(string[] arr_att, string[] arr_value)
        {
            string res = "";
            for (int i = 0; i < arr_att.Length; i++)
            {
                if (arr_value[i] != null)
                {
                    if (arr_att.Length == 0)
                    {
                        res = ShowAttribute(arr_att[i], arr_value[i]);
                    }
                    else
                    {
                        res += "," + ShowAttribute(arr_att[i], arr_value[i]);
                    }
                }

            }
            return res = "";
        }
        /// <summary>
        /// 获取Echart数据集合(根据传入的数据格式，自动转换成list集合)
        /// </summary>
        /// <param name="dt">传一行多列数据，或者多行两列(name,value)数据</param>
        /// <param name="direction">默认为垂直数据（Group By）  传 v、h</param>
        /// <returns></returns>
        public static List<EchartSeries> GetEchartSeriesList(DataTable dt)
        {
            List<EchartSeries> series = new List<EchartSeries>();


            if (dt.Columns.Count == 2)
            {
                //垂直格式（两列，多行）
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string name = dt.Rows[i]["name"].ToString();
                    string value = dt.Rows[i]["value"].ToString();
                    series.Add(new EchartSeries { Name = name, Value = value });
                }
            }
            else if (dt.Rows.Count == 1)
            {
                //水平格式（一行，多列）
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    string name = dt.Columns[i].ColumnName.ToString();
                    string value = dt.Rows[0][i].ToString();
                    series.Add(new EchartSeries { Name = name, Value = value });
                }
            }

            return series;
        }


        /// <summary>
        /// 获取表名称（'Table1','Table2','Table3'）
        /// </summary>
        /// <param name="ds"></param>
        /// <returns></returns>
        private static string GetTableNames(DataSet ds)
        {
            string res = "";
            for (int i = 0; i < ds.Tables.Count; i++)
            {
                if (i == 0)
                {
                    res += "\"" + ds.Tables[i].TableName + "\"";
                }
                else
                {
                    res += ",\"" + ds.Tables[i].TableName + "\"";
                }
            }
            return res;
        }


        /// <summary>
        /// 获取名称字符串，如：['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月']
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        private static string GetNames(DataTable dt)
        {
            string res = "";
            List<EchartSeries> serieslist = GetEchartSeriesList(dt);

            for (int i = 0; i < serieslist.Count; i++)
            {
                string value = serieslist[i].Name;
                if (i == 0)
                {
                    res += "'" + value + "'";
                }
                else
                {
                    res += ",'" + value + "'";
                }
            }
            return res;
        }

        /// <summary>
        /// 获取值得字符串，如：['13','0','0','0','0','0','0','0','0','0','0','0']
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        private static string GetValues(DataTable dt)
        {
            string res = "";
            List<EchartSeries> serieslist = GetEchartSeriesList(dt);

            for (int i = 0; i < serieslist.Count; i++)
            {
                string value = serieslist[i].Value;
                if (i == 0)
                {
                    res += value;
                }
                else
                {
                    res += "," + value;
                }
            }
            return res;
        }

        /// <summary>
        /// 获取名称和值。如：[{value: 6, name: '四川省' },{ value: 7, name: '资阳市' }]
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        private static string GetNameAndValues(DataTable dt)
        {
            string res = "";
            List<EchartSeries> serieslist = GetEchartSeriesList(dt);

            for (int i = 0; i < serieslist.Count; i++)
            {
                string name = serieslist[i].Name;
                string value = serieslist[i].Value;
                if (i == 0)
                {
                    res += "{ value: " + value + ", name: '" + name + "' }";
                }
                else
                {
                    res += ",{ value: " + value + ", name: '" + name + "' }";
                }
            }
            return res;
        }

        /// <summary>
        /// 获取Echart数据集
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        private static string GetSery(DataTable dt, string type = "bar")
        {
            string res = "";
            switch (type)
            {
                case "bar":
                    res += "{";
                    res += "name:'" + dt.TableName + "',";
                    res += "type:'" + type + "',";
                    res += "data:[" + GetValues(dt) + "],";
                    res += "markPoint : {data : [{type : 'max', name: '最大值'},{type : 'min', name: '最小值'}]},";
                    res += "markLine : {data : [{type : 'average', name: '平均值'}]}";
                    res += "}";
                    break;
                case "line":
                    goto case "bar";
                case "pie":
                    res += "{";
                    res += "type:'pie',";
                    res += "radius : '55%',";
                    res += "center: ['50%', '60%'],";
                    res += "data:[" + GetNameAndValues(dt) + "]";
                    res += "}";
                    break;
            }

            return res;
        }
        /// <summary>
        /// 获取Echart数据集
        /// </summary>
        /// <param name="ds"></param>
        /// <returns></returns>
        private static string GetSeries(DataSet ds, string type = "bar")
        {
            string res = "";
            for (int i = 0; i < ds.Tables.Count; i++)
            {
                if (i == 0)
                {
                    res += GetSery(ds.Tables[i], type);
                }
                else
                {
                    res += "," + GetSery(ds.Tables[i], type);
                }
            }
            return res;
        }
        #endregion

    }

    /// <summary>
    /// Echart数据模型
    /// </summary>
    public class EchartSeries
    {
        /// <summary>
        /// 名称
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 值
        /// </summary>
        public string Value { get; set; }
    }

    /// <summary>
    /// Echart报表属性
    /// </summary>
    public class EchartAttribute
    {
        private bool _calculable = true;

        private bool _title_show = true;
        private string _title_x = "center";

        private bool _tooltip_show = true;
        private bool _toolbox_show = true;

        private string _legend_x = "left";

        /// <summary>
        /// 报表类型
        /// </summary>
        public string Type { get; set; }

        /// <summary>
        /// 是否显示标题
        /// </summary>
        public bool title_show { get { return _title_show; } set { _title_show = value; } }
        /// <summary>
        /// 标题
        /// </summary>
        public string title_text { get; set; }
        /// <summary>
        /// 副标题
        /// </summary>
        public string title_subtext { get; set; }
        /// <summary>
        /// 标题横向位置
        /// </summary>
        public string title_x { get { return _title_x; } set { _title_x = value; } }
        /// <summary>
        /// 标题纵向位置
        /// </summary>
        public string title_y { get; set; }
        /// <summary>
        /// 是否显示提示信息
        /// </summary>
        public bool tooltip_show { get { return _tooltip_show; } set { _tooltip_show = value; } }
        /// <summary>
        /// 提示信息显示方式
        /// </summary>
        public string tooltip_trigger { get; set; }
        /// <summary>
        /// 方向
        /// </summary>
        public string legend_orient { get; set; }
        /// <summary>
        /// 数据
        /// </summary>
        public string legend_data { get; set; }
        /// <summary>
        /// 横向位置
        /// </summary>
        public string legend_x { get { return _legend_x; } set { _legend_x = value; } }

        public bool toolbox_show { get { return _toolbox_show; } set { _toolbox_show = value; } }

        /// <summary>
        /// 是否允许拖动
        /// </summary>
        public bool calculable { get { return _calculable; } set { _calculable = value; } }

    }


}
